<!-- 搜索表单还没画，暂时不想做》。《 -->
<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>课程管理</el-breadcrumb-item>
      <el-breadcrumb-item>课程信息</el-breadcrumb-item>
    </el-breadcrumb>
    <div class="search">
      <label>课程号:<input type="text" placeholder="请输入课程号" v-model="courseId" /></label>
      <label>课程名:<input type="text" placeholder="请输入课程名" v-model="name" /></label>
    </div>
    <el-table :data="tableData" :height="height">
      <el-table-column type="expand">
        <template slot-scope="scope">
          <el-form label-position="left" inline class="demo-table-expand">
            <el-form-item label="学期">
              <span>{{ scope.row.term}}</span>
            </el-form-item>
            <el-form-item label="学时">
              <span>{{ scope.row.period }}</span>
            </el-form-item>
            <el-form-item label="上课时间">
              <span>{{ scope.row.timeSchedule }}</span>
            </el-form-item>
            <el-form-item label="上课地点">
              <span>{{ scope.row.location }}</span>
            </el-form-item>
          </el-form>
        </template>
      </el-table-column>
      <el-table-column label="课程号" width="140">
        <template slot-scope="scope">
          <span>{{ scope.row.courseId }}</span>
        </template>
      </el-table-column>
      <el-table-column label="学院号" width="140">
        <template slot-scope="scope">
          <span>{{ scope.row.collegeId }}</span>
        </template>
      </el-table-column>
        <el-table-column label="学分" width="140">
        <template slot-scope="scope">
          <span>{{ scope.row.credit }}</span>
        </template>
      </el-table-column>
      <el-table-column label="课程名" width="140">
        <template slot-scope="scope">
          <span>{{ scope.row.name }}</span>
        </template>
      </el-table-column>
        <el-table-column label="学时" width="140">
        <template slot-scope="scope">
          <span>{{ scope.row.period }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200">
        <template slot-scope="scope">
          <el-button size="mini" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
          <el-button size="mini" type="danger" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
        :page-sizes="[1, 2, 3]"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        layout="total, sizes, prev, pager, next, jumper"
        :total="firstFrom.total">
      </el-pagination>
    <!-- 编辑弹窗 -->
     <el-dialog
      title="编辑课程信息"
      :visible.sync="dialogFormVisible"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <el-form :model="ruleForm" :rules="rules" ref="ruleForm" :label-width="formLabelWidth">
        <el-form-item label="课程号" prop="courseId">
          <el-input v-model="ruleForm.courseId"></el-input>
        </el-form-item>
        <el-form-item label="学院号" prop="collegeId">
          <el-input v-model="ruleForm.collegeId"></el-input>
        </el-form-item>
        <el-form-item label="学分" prop="credit">
          <el-input v-model.number="ruleForm.credit"></el-input>
        </el-form-item>
        <el-form-item label="课程名" prop="name">
          <el-input v-model="ruleForm.name"></el-input>
        </el-form-item>
        <el-form-item label="学时" prop="period">
          <el-input  v-model="ruleForm.period"></el-input>
        </el-form-item>
        <el-form-item label="学期" prop="term">
          <el-input  v-model="ruleForm.term"></el-input>
        </el-form-item>
        <el-form-item label="上课时间" prop="timeSchedule">
          <el-input  v-model="ruleForm.timeSchedule"></el-input>
        </el-form-item>
        <el-form-item label="上课地点" prop="location">
          <el-input  v-model="ruleForm.location"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelEdit">取 消</el-button>
        <el-button type="primary" @click="updateEdit(ruleForm)">保存</el-button>
      </div>
    </el-dialog> 
  </div>
</template>


<script>
export default {
  name: "CourseInfo",
  data() {
    return {
      firstFrom:{
        // 用于保存初始的条数
      total:0,
      },
      pageFrom:{
        page: 1,
        pageSize: 3
      },
      title: "课程信息表",
      courseId:'',	
      courseName:'',
      studentId:'',
      studentName:'',	
      teacherId:'',
      teacherName:'',
      name:'',
      // 用于表格渲染
      tableData: [],
      height: document.documentElement.clientHeight - 120,
      dialogFormVisible: false,
      formLabelWidth: "100px",
      //用于搜索的框
      searchForm:{},
      //用于修改的框
      ruleForm: {courseId:'',name:'',collegeId:'',credit:'',term:'',period:'',timeSchedule:'',location:''},
      rules: {
        courseId: [{ required: true, message: "请填写课程ID" }],
        courseName: [{ required: true, message: "请填写课程名称" }],
        collegeId: [{ required: true, message: "请填写学院ID" },
        {
      validator: (rule, value, callback) => {
        if (!Number.isInteger(value)) {
          callback(new Error("学院ID必须为整数"));
        } else {
          callback();
        }
      }
    }
      ],

        credit: [{ required: true, message: "请填写学分" }],
        term: [{ required: true, message: "请填写学期" },
        {
      validator: (rule, value, callback) => {
        if (!Number.isInteger(value)) {
          callback(new Error("学期必须为整数"));
        } else {
          callback();
        }
      }
    }
      ],
        period: [{ required: true, message: "请填写学时" }],
        timeSchedule: [{ required: true, message: "请填写时间安排" }],
        location: [{ required: true, message: "请填写地点安排" }]
      },
    };
  },
  methods: {
    // 数据分页
    handleCurrentChange(currentPage) {
      this.pageFrom.page = currentPage;
      // 每次更改都要请求一次tabledata数据，在后端做数据分页！>.<！
      this.getcourseTable()
    },
    handleSizeChange(size) {
      this.pageFrom.pageSize = size;
      this.getcourseTable()
      // 每次更改都要请求一次tabledata数据，在后端做数据分页！>.<！
    },
    // 获取课程信息表
    async getcourseTable() {
      const dataToSerialize = { ...this.pageFrom };
      if (this.courseID) {
    dataToSerialize.courseId=this.courseID;
}

     if (this.name) {
    dataToSerialize.name=this.name;
}
    // JSON化
    const config = {
      headers: {
        'Content-Type': 'application/json',
        'token':`${localStorage.getItem("token")}`// Custom request header
      }
    };
    try {
      const { data: res } = await this.$http.post(`api/admin/course/page`,JSON.stringify(dataToSerialize),config);
      if (res.status !== 500) {
        this.tableData=res.data.records;
      } else {
        this.$message.error('获取失败');
      }
    } catch (error) {
      // Handle request error
      console.error('Request Error:', error);
      this.$message.error('请求失败');
  }
    
    },
    // 获取课程初始数据
    async getFirstcourseTable() {
    // JSON化
    const config = {
      headers: {
        'Content-Type': 'application/json',
        'token':`${localStorage.getItem("token")}`// Custom request header
      }
    };
    try {
      const { data: res } = await this.$http.post(`api/admin/course/page`,JSON.stringify(this.pageFrom),config);
      if (res.status !== 500) {
        this.$message.success('成功获取课程成绩');
        this.tableData=res.data.records;
        this.firstFrom.total = res.data.total; // 保存总条数
      } else {
        this.$message.error('获取失败');
      }
    } catch (error) {
      // Handle request error
      console.error('Request Error:', error);
      this.$message.error('请求失败');
  }
    
    },
    //删除课程信息,还可以检索名字
    async deletecourseInfo(ID,Name) {
      const dataToSerialize = {};
      if (ID) {
    dataToSerialize.courseId=ID;
}

        if (Name) {
        dataToSerialize.name=Name;
    }
    // JSON化
    const config = {
      headers: {
          'Content-Type':'application/json',
          'token':`${localStorage.getItem("token")}`
        }
      };
    try {
      const { data: res } = await this.$http.delete('api/admin/course/delete',{data:JSON.stringify(dataToSerialize), // 请求数据
    headers: config.headers })
      if (res.status !== 500) {
        this.$message.success('成功删除课程信息');
        // 重新调用获取表格的代码
        this.getFirstcourseTable();
      } else {
        this.$message.error('删除失1败');
      }
    } catch (error) {
      // Handle request error
      console.error('Request Error:', error);
      this.$message.error('删除失败');
  }
    },
    // 启动编辑功能
    handleEdit(index, row) {
      this.dialogFormVisible = true;
      this.ruleForm = { ...row };

    },
    // 保存编辑按钮
    async updateEdit(params) {
      if (confirm("是否确认所编辑的内容！")){
    // JSON化
    const config = {
      headers: {
        'Content-Type': 'application/json',
        'token':`${localStorage.getItem("token")}`// Custom request header
      }
    };
    try {
      const { data: res } = await this.$http.put(`api/admin/course/update`,JSON.stringify(params),config);
      if (res.status !== 500) {
        this.$message.success('成功编辑课程信息');
        // 重新调用获取表格的代码
        this.getcourseTable();
        this.dialogFormVisible = false;
      } else {
        this.$message.error('编辑失败');
      }
    } catch (error) {
      // Handle request error
      console.error('Request Error:', error);
      this.$message.error('编辑失败');
  }
}
},
    // 取消编辑按钮
    cancelEdit() {
      if (confirm("是否确认取消所编辑的内容！")) {
        this.dialogFormVisible = false;
      }
    },
    // 删除功能
    handleDelete(index, row) {
      if (confirm("是否确认删除？")) {
        this.deletecourseInfo(row.courseId,row.name);
      }
    },
  },

  mounted() {
    if(localStorage.getItem("type") !== 'admin'){this.$router.push(`/login`);this.$message.error('权限不够');}
    this.getFirstcourseTable();
  },
};
</script>

<style lang="less" scoped>
.search {
  background-color: #fff;
  padding:10px 5px;
  font-size:14px;
  text-align: right;
}
.search label {
  margin-right:30px;
}
.search input {
  margin-left:10px;
  width:160px;
  outline: none;
}
.el-breadcrumb {
  padding-bottom: 10px;
}
.el-table {
  width: 100%;
}
.demo-table-expand {
  font-size: 0;
}
.demo-table-expand label {
  width: 90px;
  color: #99a9bf;
}
.demo-table-expand .el-form-item {
  margin-left: 70px;
  margin-bottom: 0;
  min-width: 40%;
  max-width: 84%;
}
/deep/ .el-table .el-table__cell {
  padding: 8px 0;
}
/deep/ .el-dialog {
  margin-top: 10px !important;
}
/deep/.el-dialog__body {
  padding: 10px 20px !important;
  font-size: 12px !important;
}
/deep/.el-dialog__footer {
  padding: 0px 20px 10px !important;
}
</style>
